//
//  ViewController.m
//  gundongtupian10
//
//  Created by apple on 15/7/29.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;

@end

@implementation ViewController



- (void)viewDidLoad {
    
    [super viewDidLoad];
   CGSize size = self.scrollview.frame.size;
    
   
    
    for (int i = 0; i<5; i++) {
        UIImageView *image = [[UIImageView alloc] init];
        
        image.image = [UIImage imageNamed:[NSString stringWithFormat:@"img_%02d",i]];
        
        image.frame = CGRectMake(size.width*i,0,size.width,size.height);
        [self.scrollview addSubview:image];
        
    }
     self.scrollview.contentSize = CGSizeMake(size.width*5, 0);
    
    self.pageControl.currentPage = 5;
    
    self.scrollview.showsHorizontalScrollIndicator = NO;
    self.scrollview.pagingEnabled = YES;
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(nextImage:) userInfo:nil repeats:YES];
    
    NSRunLoop *loop = [NSRunLoop currentRunLoop];
    
    [loop addTimer:timer forMode:NSRunLoopCommonModes];
    
    
    self.scrollview.delegate = self;
}

- (void)nextImage:(NSTimer *)timer
{
    int page =self.pageControl.currentPage;
    NSLog(@"page = %d",page);
    if (  page == self.pageControl.numberOfPages-1) {
        page = 0;
    }else
    {
        page++;
    }
    
    NSLog(@"numberOfPages = %d",self.pageControl.numberOfPages);
    self.pageControl.currentPage = page;
    
    [UIView animateWithDuration:1 animations:^{
        
        self.scrollview.contentOffset = CGPointMake(page*self.scrollview.frame.size.width, 0);
        
    }];
     
     
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int count = scrollView.contentOffset.x /scrollView.frame.size.width;
    self.pageControl.currentPage = count;
}

@end
